package com.gitee.candy.file;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import java.util.zip.GZIPOutputStream;

/**
 * @author ：suyanlong
 * @date ：Created in 2020/10/25 15:33
 * @description：文件操作
 * @version: 1.0
 */
public class FileUtils {

    private static final Log log = LogFactory.getLog(FileUtils.class);

    public static void main(String[] args) {
        System.out.println(System.getProperty("os.name"));
        mkdirs("C:\\Users\\Administrator\\Desktop\\fsdownload\\test\\candy");
        delete("C:\\Users\\Administrator\\Desktop\\fsdownload\\test\\candy");
    }

    /**
     * 当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
     *
     * @param destPath 存放目录
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        //当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
        mkdirs(file);
    }

    public static void mkdirs(File file) {
        //当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static boolean delete(String targetPath) {
        File file = new File(targetPath);
        return delete(file);
    }

    public static boolean delete(File file) {
        File[] files = file.listFiles();
        if (files != null)
            for (File fileFor : files) {
                if (fileFor.isDirectory()) {
                    delete(fileFor);
                } else {
                    fileFor.delete();
                }
            }
        return file.delete();
    }

    public static boolean exists(String path) {
        File file = new File(path);
        return exists(file);
    }

    public static boolean exists(File file) {
        return file.exists();
    }

    /**
     * 读取文件
     */
    public static String readFile(String pathname) {
        StringBuffer str = new StringBuffer();
        //防止文件建立或读取失败，用catch捕捉错误并打印
        try (FileReader reader = new FileReader(pathname);
             BufferedReader br = new BufferedReader(reader)
        ) {
            String line;//逐行读取
            while ((line = br.readLine()) != null) {
                str.append(line);
                str.append("\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return str.toString();
    }

    /**
     * 写入文件，如果文件存在，追加写入
     */
    public static void writeFile(String pathname, String content) {
        try {
            File writeName = new File(pathname);
            try (FileWriter writer = new FileWriter(writeName, true);
                 BufferedWriter out = new BufferedWriter(writer)
            ) {
                out.write(content);
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取某路径下的文件全路径 【非递归】
    public static List<String> getFiles(String path, boolean subdirectory) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
                //文件名，不包含路径
                String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory() && subdirectory) {
                // 递归
                files.addAll(getFiles(tempList[i].getPath(), true));
            }
        }
        return files;
    }

    /**
     * 创建一个临时文件
     *
     * @param url 远端文件Url
     * @return File
     */
    public static File getFile(String url) {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        File file = null;

        URL urlfile;
        try {
            // 创建一个临时路径
            file = File.createTempFile("file", fileName);
            log.info("tempFile:-> " + file.getAbsolutePath());
            //下载
            urlfile = new URL(url);

            try (InputStream inStream = urlfile.openStream();
                 OutputStream os = new FileOutputStream(file);) {
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            }
        } catch (Exception e) {
            log.error("创建临时文件出错：-》" + e.getMessage());
        } finally {
            if (file != null) {
                file.delete();
            }
        }
        return file;
    }

    /**
     * 将网络文件路径转换成base64
     *
     * @param url 路径
     * @return base64
     */
    public static String getFileBase64(String url) {
        byte[] fileBytes = getFileBytes(url);
        return Optional.ofNullable(fileBytes).isPresent() ? Base64.getEncoder().encodeToString(fileBytes) : null;
    }

    /**
     * 将网络文件路径转换成 byte[]
     *
     * @param url 路径
     * @return byte[]
     */
    public static byte[] getFileBytes(String url) {
        URL urlfile;
        InputStream in = null;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            //建一个空的字节数组
            byte[] result = null;
            urlfile = new URL(url);

            in = urlfile.openStream();// 获取图片的输入流
            byte[] buf = new byte[1024];
            //用来定义一个准备接收图片总长度的局部变量
            int len;
            //将流的内容读取到buf内存中
            while ((len = in.read(buf)) > 0) {
                //将buf内存中的内容从0开始到总长度输出出去
                out.write(buf, 0, len);
            }
            //将out中的流内容拷贝到一开始定义的字节数组中
            result = out.toByteArray();
            //通过util包中的Base64类对字节数组进行base64编码
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return null;
    }

    /**
     * base64 -> 本地文件
     *
     * @param base64Str base64
     * @param filePath  本地文件路径
     * @return
     * @throws IOException
     */
    public static Boolean generateFile(String base64Str, String filePath) throws IOException {
        if (base64Str == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        //base64解码 对字节数组字符串进行base64解码并生成文件
        byte[] byt = decoder.decodeBuffer(base64Str);
        for (int i = 0; i < byt.length; i++) {
            //调整异常数据
            if (byt[i] < 0) {
                byt[i] += 256;
            }
        }

        OutputStream out = null;
        InputStream input = new ByteArrayInputStream(byt);
        try {
            //生成指定格式的文件
            out = new FileOutputStream(filePath);
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = input.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
        return true;
    }

    public static void saveFile(String path, byte[] bytes) throws Exception {
        if (bytes != null) {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();
        }
    }

    public static byte[] getGzipBytesByFile(String pathStr) {
        File file = new File(pathStr);
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();

//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//            GZIPOutputStream gzip = new GZIPOutputStream(out);
//            gzip.write(bos.toByteArray());
//            gzip.close();

            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
